package com.dsh.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsh.common.response.Result;
import com.dsh.mapper.CategoryMapper;
import com.dsh.mapper.GoodsMapper;
import com.dsh.model.CategoryEntity;
import com.dsh.model.GoodsBrowserLog;
import com.dsh.model.GoodsBrowserLogEntity;
import com.dsh.model.GoodsEntity;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class GoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;


    public Page<GoodsEntity> findPage(Integer pageNum, Integer pageSize) {
        Page<GoodsEntity> page = new Page<>(pageNum,pageSize);
        return goodsMapper.selectPage(page, Wrappers.emptyWrapper());
    }

    public Result save(GoodsEntity goodsEntity) {
        if (goodsEntity.getId()!=null){
            redisTemplate.delete("Goods_"+goodsEntity.getId());
            goodsMapper.updateById(goodsEntity);
            return new Result(true,"1","修改成功");
        }else {
            goodsMapper.insert(goodsEntity);
            return new Result(true,"1","添加成功");
        }

    }


    public GoodsEntity findById(String uname,Long id) {
        //(2)考虑到流量大时可能产生大量访问记录，利用RabbitMQ进行异步处理，减轻压力

        //(6)利用Redis对商品访问次数进行记录，保证并发情况下不丢次数
        redisTemplate.opsForValue().increment("Goods_Count_"+id,1);

        //(5)利用Redis对商品详情页信息进行缓存，减少数据库访问
        GoodsEntity goodsEntity = (GoodsEntity) redisTemplate.opsForValue().get("Goods_" + id);
        if (goodsEntity==null){
            //缓存中为空 从数据库中查找赋值再返回
            goodsEntity= goodsMapper.selectById(id);
            redisTemplate.opsForValue().set("Goods_"+id,goodsEntity);
            this.browserLog(uname,goodsEntity);
            return goodsEntity;
        }
        this.browserLog(uname,goodsEntity);
        //直接返回
        return goodsEntity;
    }

    //浏览日志
    private void browserLog(String uname,GoodsEntity goodsEntity){
        GoodsBrowserLogEntity goodsBrowserLog = new GoodsBrowserLogEntity();
        goodsBrowserLog.setUserName(uname);
        goodsBrowserLog.setGoodsId(goodsEntity.getId());
        goodsBrowserLog.setName(goodsEntity.getName());
        CategoryEntity categoryEntity = categoryMapper.selectById(goodsEntity.getCatalogId());
        goodsBrowserLog.setCatalogName(categoryEntity.getName());
        goodsBrowserLog.setLogTime(new Date());
        System.out.println("----------------Mq----------------"+ goodsBrowserLog);
        rabbitTemplate.convertAndSend("ex_1911A_1","routingKey4", goodsBrowserLog);
    }

}
